import mammoth from 'mammoth'; // mammoth库是一个用于将.docx文件转换为HTML的工具，因此它主要支持预览Microsoft Word的.docx文件。

import { uploadImageToAliOS } from '../../../utils/uploadImageToAliOS';
import { dataURLtoBlob } from '../../../utils/handleImagesInArticle';

const UPLOAD_ERROR = `${import.meta.env.VITE_OSS_BUCKET_URL}/default/upload-error.png`;

// 解析文档
export const handleLoad = async (loadEvent: ProgressEvent<FileReader>, filterImage = false): Promise<string> => {
  if (!loadEvent.target || !loadEvent.target.result) {
    throw new Error('文件读取结果为空');
  }

  const arrayBuffer = loadEvent.target.result as ArrayBuffer;
  try {
    const resultObject = await mammoth.convertToHtml({
      arrayBuffer: new Uint8Array(arrayBuffer),
    });
    return await processHtml(resultObject.value, filterImage);
  } catch (error) {
    console.error('处理文件失败:', error);
    if (error.message.includes('End of data reached')) {
      throw new Error('文件损坏或不完整，请查后再试');
    } else {
      throw error;
    }
  }
};

// 处理图片的逻辑
async function processHtml(html: string, filterImage: boolean): Promise<string> {
  let tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  checkLimits(tempDiv); // 检查文档限制

  const imgTags = tempDiv.querySelectorAll('img');

  if (filterImage) {
    // 如果filterImage为true，移除所有图片标签
    imgTags.forEach((img) => img.remove());
  } else if (imgTags.length > 0) {
    // 如果filterImage为false，处理图片标签
    await handleImages(imgTags).catch((error) => {
      console.error('处理图片失败:', error);
      throw new Error('处理图片失败');
    });
  }
  return tempDiv.innerHTML;
}

// 检查文档的限制条件，如图片数量和文本长度
function checkLimits(element: HTMLElement) {
  const imgTags = element.querySelectorAll('img');
  if (imgTags.length > 100) {
    throw new Error('文档图片数量超过一百张，请删减图片后再试');
  }

  const textContent = element.textContent || '';
  if (textContent.length > 5000) {
    throw new Error('文档字数超过5000，请删减部分文字后再试');
  }
}

async function handleImages(imgTags: NodeListOf<HTMLImageElement>): Promise<void> {
  const imageUploadPromises = Array.from(imgTags).map(async (img, index) => {
    try {
      // word文档导入解析过来的图片均为base64
      const base64Src = img.getAttribute('src');
      if (!base64Src) throw new Error('图片缺失Base64源数据');
      const newSrc = dataURLtoBlob(base64Src);
      const newUrl = await uploadImageToAliOS(newSrc);
      img.setAttribute('src', newUrl);
    } catch (error) {
      img.setAttribute('src', UPLOAD_ERROR);
    }
  });
  await Promise.all(imageUploadPromises);
}
